package com.yapmadanolme.dao;

import java.sql.*;
import java.io.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;


import com.yapmadanolme.model.Wish;
import java.util.ArrayList;
import java.util.HashMap;
import net.arnx.jsonic.JSON;

/**
 *
 * @author Mehmet
 */

public class WishesDao extends HttpServlet
{
     Connection connection;

     @Override
     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {
        int command = Integer.parseInt(request.getParameter("type"));
        HttpSession session = request.getSession();

        switch(command)
        {
            case 1: //add wish
                String wish = request.getParameter("wish");
                int authorId= Integer.parseInt(request.getParameter("id"));
                int wishID=insertWish(wish,authorId);
                response.getWriter().write(wishID);
                break;
            case 2: //update wish
                int wishId= Integer.parseInt(request.getParameter("id"));
                int updateType= Integer.parseInt(request.getParameter("updateType"));
                updateWish(wishId, updateType);
                break;
            case 3:// get wishlist of a user
                int authorid= Integer.parseInt(request.getParameter("id"));
                List<Wish> wishList=selectWishes(authorid);
                /*either use JSON or XML*/
		HashMap result = new HashMap();
		result.put("result", wishList);
		result.put("array_size", wishList.size());
		String enc = JSON.encode(result);
		response.getWriter().write(enc);
                break;
        }
     }
    public void openConnection()// opens Database connection
    {
        String dbUrl = "jdbc:mysql://localhost:3306/yapmadanolmedb";
        String username = "root";
        String password ="1";

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(dbUrl, username,password);

        } //end try
        catch(ClassNotFoundException e) { e.printStackTrace();   }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
    public void closeConnection()//closes database connection
    {
        try {
            connection.close();
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private List<Wish> selectWishes(int id) // returns wish list of given user
    {
        List<Wish> wishList=new ArrayList<Wish>();
        String query="select * from wishes where authorID=?";
        openConnection();
        try {
            PreparedStatement stmt=connection.prepareStatement(query);
            stmt.setInt(1, id);
            ResultSet rs=stmt.executeQuery();
            while(rs.next())
            {
                Wish newWish= new Wish();
                newWish.setAuthorId(rs.getInt("authorID"));
                newWish.setWishId(rs.getInt("wishID"));
                newWish.setWish(rs.getString("wishText"));
                newWish.setTime(rs.getTimestamp("dateEntered"));
                newWish.setLikeCnt(rs.getInt("like"));
                newWish.setDislikeCnt(rs.getInt("dislike"));
                newWish.setWantCnt(rs.getInt("want"));
                newWish.setDoneCnt(rs.getInt("done"));

                wishList.add(newWish);
            }
            rs.close();
            stmt.close();
            return wishList;
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

     private int insertWish(String wish,int id) //insert a new wish to the given user
     {
         int wishID=0;
         String query="insert into wishes (authorID, wishText) Values (?,?)";
         openConnection();
         try {
            PreparedStatement stmt=connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, id);
            stmt.setString(2,wish);
            stmt.executeUpdate();
            ResultSet rs=stmt.getGeneratedKeys();
            if(rs.next())
                wishID=rs.getInt(1);
            rs.close();
            stmt.close();
        }
         catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        closeConnection();
        return wishID;
     }

     private int updateWish(int wishID,int type) //insert a new wish to the given user
     {
         String query=new String();
         switch(type)
         {
             case 1:    //like
                query="update wishes set wishes.like=wishes.like+1 where wishID=?";
                break;
             case 2:    //dislike
                 query="update wishes set wishes.dislike=wishes.dislike+1 where wishID=?";
                 break;
             case 3:    //want
                 query="update wishes set wishes.want=wishes.want+1 where wishID=?";
                 break;
             case 4:    //done
                 query="update wishes set wishes.done=wishes.done+1 where wishID=?";
                 break;
         }
         openConnection();
         try {
            PreparedStatement stmt=connection.prepareStatement(query);
            stmt.setInt(1, wishID);
            stmt.executeUpdate();
            stmt.close();
        }
         catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        closeConnection();
        return wishID;
     }
}
